/*
 * Wantmore - Service Delivery Platform.
 *
 * $Id: AlbumListFormController.java 60 2010-10-13 07:26:24Z alexey.batyuta@gmail.com $
 *
 * Copyright 2010 by Sunbay Software Crimea Ltd.
 * All rights reserved
 */
package ua.crimea.bat.ss.forms;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import ua.crimea.bat.ss.model.beans.Album;
import ua.crimea.bat.ss.services.PhotoAlbumsService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * User: bat
 * Date: Mar 26, 2010
 * Time: 8:47:10 AM
 */
@Controller("albumListFormController")
@RequestMapping("/albums/list")
public class AlbumListFormController extends AbstractController implements org.springframework.web.servlet.mvc.Controller {
    @Autowired
    protected PhotoAlbumsService photoAlbumsService;

    public AlbumListFormController() {
    }

    public void setPhotoAlbumsService(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    public PhotoAlbumsService getPhotoAlbumsService() {
        return photoAlbumsService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    public AlbumListFormController(PhotoAlbumsService photoAlbumsService) {
        setPhotoAlbumsService(photoAlbumsService);
    }

    @Override
    @RequestMapping(method = RequestMethod.GET)
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Collection<Album> results = this.photoAlbumsService.findAlbums(false);
        //logger.info("Returning hello view");
        ModelAndView modelAndView = new ModelAndView("albums/list");
        if (results.size() > 0) {
            // multiple owners found
            modelAndView.addObject("selections", results);

        } else {
            // 1 owner found
            /*album = results.iterator().next();
               return "redirect:/albums/" + album.getId();*/
            modelAndView.addObject("selections", null);
        }
        return modelAndView;
    }
    @RequestMapping(value = "/albums/list/{albumId}/delete",method = RequestMethod.DELETE)
    public String deleteAlbum(@PathVariable int albumId) {
        photoAlbumsService.deleteAlbum(albumId);
        return "redirect:/albums/list";
    }
}
